package com.imooc.food.service;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.imooc.food.dao.OrderDetailDao;
import com.imooc.food.dto.OrderMessageDTO;
import com.imooc.food.entity.OrderDetailPO;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * ProjectName food
 *
 * @author xieyucan
 * <br>CreateDate 2022/9/22 17:57
 */
@Service
public class SendMessage {

    @Resource
    private RabbitTemplate rabbitTemplate;

    @Resource
    private OrderDetailDao orderDetailDao;

    private ObjectMapper objectMapper=new ObjectMapper();

    public void sendPractice() throws JsonProcessingException {
        OrderDetailPO orderDetailPO = new OrderDetailPO();
        orderDetailPO.setAccountId(152);
        orderDetailPO.setAddress("hhh");
        orderDetailDao.insert(orderDetailPO);

        OrderMessageDTO orderMessageDTO = new OrderMessageDTO();
        orderMessageDTO.setOrderId(orderDetailPO.getId());
        orderMessageDTO.setAccountId(orderDetailPO.getAccountId());
        String messageToSend = objectMapper.writeValueAsString(orderMessageDTO);
        Message message = new Message(messageToSend.getBytes());
        CorrelationData correlationData = new CorrelationData();
        correlationData.setId(orderDetailPO.getId().toString());
        rabbitTemplate.send(
                "exchange.my.practice",
                "key.my",
                message,
                correlationData
        );
    }


    public void sendFanout() throws JsonProcessingException {
        OrderDetailPO orderDetailPO = new OrderDetailPO();
        orderDetailPO.setAccountId(188);
        orderDetailPO.setAddress("fanout");
        orderDetailDao.insert(orderDetailPO);

        OrderMessageDTO orderMessageDTO = new OrderMessageDTO();
        orderMessageDTO.setOrderId(orderDetailPO.getId());
        orderMessageDTO.setAccountId(orderDetailPO.getAccountId());
        String messageToSend = objectMapper.writeValueAsString(orderMessageDTO);
        Message message = new Message(messageToSend.getBytes());
        CorrelationData correlationData = new CorrelationData();
        correlationData.setId(orderDetailPO.getId().toString());
        rabbitTemplate.send(
                "exchange.my.fanout",
                "key.fanout1",
                message,
                correlationData
        );
    }



}
